import type { App } from 'vue';

import { excelDataHandler, initKanban, RequestContentTypeEnum } from '@eacloud/kanban';

import { dbQuery, getDbLinkNodes } from '@/api/report/db';
import { useRootSetting } from '@/hooks/setting/useRootSetting';
import { useI18n } from '@/hooks/web/useI18n';
import { updateDarkTheme } from '@/logics/theme/dark';
import { router } from '@/router';
import { store } from '@/store';
import { useLocaleStoreWithOut } from '@/store/modules/locale';
import { request } from '@/utils/request/axios';

/**
 * 初始化模块包配置
 * @param _app 应用对象
 */
export function initPackagesConfig(_app: App) {
  const { getDarkMode } = useRootSetting();
  // 初始化看板组件
  initKanban({
    store,
    request,
    themeMode: getDarkMode.value,
    changeThemeFn: updateDarkTheme,
    getI18nFn: () => {
      const i18n = useI18n();
      return i18n;
    },
    getLocaleFn: () => {
      const localeStore = useLocaleStoreWithOut();
      return localeStore.getLocale;
    },
    watermark: true,
    router,
    designerUrl: '/report/kanban/designer',
    viewerUrl: '/report/kanban/viewer',
    customFetchFn: async (target, global, options, defaultFetchFn) => {
      let result: any = null;
      if (options === false) {
        return result;
      }
      // 全局
      const {
        // 全局请求源地址
        requestOriginUrl,
      } = global;

      if (requestOriginUrl !== undefined && requestOriginUrl !== null && requestOriginUrl !== '') {
        return await defaultFetchFn(target, global, options);
      }
      // 目标组件（优先级 > 全局组件）
      const {
        // 请求地址
        requestUrl,
        // 数据请求方式：普通、sql、文件
        requestContentType,
        // SQL 请求对象
        requestSQLContent,
        // 文件请求对象
        requestFlieContent,
      } = target;

      const { baseURL, url, method, data, params, headers, responseType } = options;

      // SQL请求
      if (requestContentType === RequestContentTypeEnum.SQL) {
        // 如果请求地址为空，则调用系统默认的接口请求，否则直接返回空对象。
        if (!requestUrl) {
          return await dbQuery({
            DbLinkId: requestSQLContent.key,
            SqlString: requestSQLContent.sql,
          });
        } else {
          return result;
        }
      }
      // 文件请求
      if (requestContentType === RequestContentTypeEnum.FILE) {
        // 如果请求地址不为空，则调用接口请求，否则直接返回空对象。
        if (requestUrl) {
          return await customFileHttp(baseURL, url, requestFlieContent.type);
        } else {
          return result;
        }
      }

      result = await request.request({ url, method, data, params, headers, responseType });
      return result;
    },
    sqlKeysFetchFn: async () => {
      const result = await getDbLinkNodes();
      if (result) {
        const sqlKeys = result.map((item) => {
          return { label: item.Name, value: item.Id.toString() };
        });
        return sqlKeys;
      }
      return [];
    },
  });
}

/**
 * 自定义HTTP文件请求
 * @param baseURL 基础请求地址
 * @param url 请求地址
 * @param fileType 文件类型
 */
export const customFileHttp = async (baseURL: string | undefined, url: string | undefined, fileType: string) => {
  let data: any = null;
  try {
    // 文件请求处理
    const result = await request.request({
      baseURL,
      url,
      method: 'get',
      responseType: 'arraybuffer', // 重要：设置响应类型为arraybuffer以接收二进制数据
    });
    // console.log(result);
    const type = fileType.toLowerCase();
    switch (type) {
      case 'excel':
        data = await excelDataHandler(result);
        break;
    }
  } catch (error) {
    console.error(error);
    window.$message.error('请求失败！');
  }
  return data;
};
